package com.shlh.saas.controller;

import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.service.SocialMediaLookupService;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.WorkbenchStatsService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/social-media-lookup")
public class SocialMediaLookupController {

    private static final Logger log = LoggerFactory.getLogger(SocialMediaLookupController.class);
    
    // 创建线程池用于并发搜索
    private final ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Autowired
    private SocialMediaLookupService socialMediaLookupService;
    
    @Autowired
    private WorkbenchStatsService workbenchStatsService;
    
    @Autowired
    private UserBalanceService userBalanceService;

    @GetMapping("")
    public Map<String, Object> lookupSocialMedia(
            @RequestParam String keyword,
            @RequestParam String type,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        // 添加调试日志
        log.info("收到社媒反查请求: 类型={}, 关键词={}, 页码={}, 页大小={}", type, keyword, page, size);

        Long userId = UserContext.getUserId();
        // 值的基本验证
        if (keyword == null || keyword.trim().isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("results", Collections.emptyList());
            errorResponse.put("total", 0);
            errorResponse.put("page", page);
            errorResponse.put("size", size);
            errorResponse.put("error", "关键词不能为空");
            return errorResponse;
        }
        
        // 类型验证
        if (!type.equals("linkedin") && !type.equals("twitter")) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("results", Collections.emptyList());
            errorResponse.put("total", 0);
            errorResponse.put("page", page);
            errorResponse.put("size", size);
            errorResponse.put("error", "类型必须是linkedin或twitter");
            return errorResponse;
        }

        // 社媒反查属于特殊操作，无论是第几页都需要扣除额度
            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getReverseLookupRemaining() < size) {
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("results", Collections.emptyList());
                errorResult.put("total", 0);
                errorResult.put("page", page);
                errorResult.put("size", size);
                errorResult.put("error", "您的反查次数余额不足，请充值后再查看");
                return errorResult;
            }
            
            // 调用服务进行查询
            Map<String, Object> result = socialMediaLookupService.lookupSocialMedia(keyword, type, page, size);
            log.info("查询结果总数: {}", result.containsKey("total") ? result.get("total") : "未知");
            
            // 如果存在错误，记录错误信息
            if (result.containsKey("error")) {
                log.warn("查询发生错误: {}", result.get("error"));
                return result;
            }
            
            // 获取实际返回的数据条数
            int actualCount = 0;
            if (result.containsKey("results") && result.get("results") instanceof List) {
                actualCount = ((List<?>) result.get("results")).size();
            }
            
            // 扣除用户反查余额
            if (actualCount > 0) {
                userBalanceService.deductReverseLookup(userId, actualCount);
            }
            
            // 增加社媒反查次数统计
            workbenchStatsService.incrementSocialMediaLookupCount(userId);
            
            return result;
    }

    /**
     * 批量社媒反查接口
     * 读取Excel文件并进行批量社媒反查，返回Excel结果文件
     */
    @PostMapping("/batch")
    public ResponseEntity<?> batchSocialMediaLookup(@RequestParam("file") MultipartFile file) {
        log.info("收到批量社媒反查请求");

        // 获取当前用户ID
        Long userId = UserContext.getUserId();

        try {
            // 检查文件
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Result.error("请选择要上传的Excel文件"));
            }

            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
                return ResponseEntity.badRequest().body(Result.error("文件格式不正确，只支持.xlsx和.xls格式"));
            }

            // 读取Excel文件
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            int totalRows = sheet.getPhysicalNumberOfRows();

            if (totalRows <= 1) {
                workbook.close();
                return ResponseEntity.badRequest().body(Result.error("上传的Excel文件没有数据"));
            }

            // 读取表头
            Row headerRow = sheet.getRow(0);
            Map<String, Integer> headerMap = new HashMap<>();
            for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    String headerName = cell.getStringCellValue().toLowerCase();
                    headerMap.put(headerName, i);
                }
            }

            // 判断查询类型和获取列索引
            String queryType = null;
            Integer linkedinUrlIndex = null;
            Integer nameIndex = null;
            Integer usernameIndex = null;
            
            // 查找各列的索引
            for (String key : headerMap.keySet()) {
                if (key.contains("linkedinUrl") || key.contains("url") || key.contains("领英链接") || key.contains("LinkedInUrl")) {
                    linkedinUrlIndex = headerMap.get(key);
                    log.info("识别到领英链接列: {}", key);
                } else if (key.contains("name") || key.contains("Name") || key.contains("姓名") || key.contains("fullName") || key.contains("全名")) {
                    nameIndex = headerMap.get(key);
                    log.info("识别到姓名列: {}", key);
                } else if (key.contains("username") || key.contains("Username") || key.contains("用户名") || key.contains("Screenname") ||  key.contains("screenname") || key.contains("screen_name")) {
                    usernameIndex = headerMap.get(key);
                    log.info("识别到用户名列: {}", key);
                }
            }
            
            // 根据列的组合判断查询类型
            if (linkedinUrlIndex != null && nameIndex != null) {
                queryType = "linkedin";
                log.info("识别到查询类型: LinkedIn（领英链接 + 姓名）");
            } else if (nameIndex != null && usernameIndex != null) {
                queryType = "twitter";
                log.info("识别到查询类型: Twitter（姓名 + 用户名）");
            } else {
                workbook.close();
                return ResponseEntity.badRequest().body(Result.error("无法识别Excel表头类型。LinkedIn查询需要'领英链接'和'姓名'列；Twitter查询需要'姓名'和'用户名'列"));
            }

            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getReverseLookupRemaining() <= 0) {
                workbook.close();
                return ResponseEntity.badRequest().body(Result.error("您的反查次数余额不足，请充值后再使用"));
            }

            // 准备结果文件
            Workbook resultWorkbook = new XSSFWorkbook();

            // 根据查询类型创建对应的sheet
            Sheet resultSheet;
            String[] headers;
            int resultCount = 0;
            
            if ("linkedin".equals(queryType)) {
                resultSheet = createSheetWithHeader(resultWorkbook, "LinkedIn数据", getLinkedInHeaders());
                headers = getLinkedInHeaders();
            } else {
                resultSheet = createSheetWithHeader(resultWorkbook, "Twitter数据", getTwitterHeaders());
                headers = getTwitterHeaders();
            }

            // 遍历数据行
            for (int rowNum = 1; rowNum < totalRows; rowNum++) {
                Row dataRow = sheet.getRow(rowNum);
                if (dataRow == null) continue;

                if ("linkedin".equals(queryType)) {
                    // LinkedIn查询：领英链接 + 姓名
                    String linkedinUrl = getCellStringValue(dataRow, linkedinUrlIndex);
                    String name = getCellStringValue(dataRow, nameIndex);
                    
                    if ((linkedinUrl == null || linkedinUrl.trim().isEmpty()) && 
                        (name == null || name.trim().isEmpty())) {
                        continue;
                    }
                    
                    try {
                        List<Map<String, Object>> results = socialMediaLookupService.searchLinkedInByUrlAndName(linkedinUrl, name);
                        if (!results.isEmpty()) {
                            for (Map<String, Object> result : results) {
                                addDataToSheet(resultSheet, result, headers);
                                resultCount++;
                            }
                        }
                    } catch (Exception e) {
                        log.error("搜索LinkedIn数据异常: linkedinUrl={}, name={}", linkedinUrl, name, e);
                    }
                    
                } else if ("twitter".equals(queryType)) {
                    // Twitter查询：姓名 + 用户名
                    String name = getCellStringValue(dataRow, nameIndex);
                    String username = getCellStringValue(dataRow, usernameIndex);
                    
                    if ((name == null || name.trim().isEmpty()) && 
                        (username == null || username.trim().isEmpty())) {
                        continue;
                    }
                    
                    try {
                        List<Map<String, Object>> results = socialMediaLookupService.searchTwitterByNameAndUsername(name, username);
                        if (!results.isEmpty()) {
                            for (Map<String, Object> result : results) {
                                addDataToSheet(resultSheet, result, headers);
                                resultCount++;
                            }
                        }
                    } catch (Exception e) {
                        log.error("搜索Twitter数据异常: name={}, username={}", name, username, e);
                    }
                }
            }

            workbook.close();

            // 检查余额是否足够
            if (userBalance.getReverseLookupRemaining() < resultCount) {
                resultWorkbook.close();
                return ResponseEntity.badRequest().body(Result.error("您的反查次数余额不足，需要扣除 " + resultCount + " 次，当前余额 " + userBalance.getReverseLookupRemaining() + " 次"));
            }

            // 移除没有数据的sheet
            removeEmptySheets(resultWorkbook);

            // 扣除用户反查余额
            if (resultCount > 0) {
                userBalanceService.deductReverseLookup(userId, resultCount);
            }

            // 增加社媒反查次数统计
            workbenchStatsService.incrementSocialMediaLookupCount(userId);

            // 将结果Excel写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            resultWorkbook.write(outputStream);
            resultWorkbook.close();

            byte[] excelBytes = outputStream.toByteArray();
            outputStream.close();

            // 设置响应头
            String resultFileName = "批量社媒反查结果_" + System.currentTimeMillis() + ".xlsx";
            HttpHeaders header = new HttpHeaders();
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            header.setContentDispositionFormData("attachment", java.net.URLEncoder.encode(resultFileName, "UTF-8"));
            header.setContentLength(excelBytes.length);

            log.info("批量社媒反查完成: 处理{}行数据，扣除{}次额度", totalRows - 1, resultCount);

            return ResponseEntity.ok()
                    .headers(header)
                    .body(excelBytes);

        } catch (Exception e) {
            log.error("批量社媒反查异常", e);
            return ResponseEntity.status(500).body(Result.error("批量社媒反查异常: " + e.getMessage()));
        }
    }

    // 创建带表头的sheet
    private Sheet createSheetWithHeader(Workbook workbook, String sheetName, String[] headers) {
        Sheet sheet = workbook.createSheet(sheetName);
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
        return sheet;
    }

    // 移除没有数据的sheet
    private void removeEmptySheets(Workbook workbook) {
        for (int i = workbook.getNumberOfSheets() - 1; i >= 0; i--) {
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet.getLastRowNum() <= 0) {
                log.info("移除空sheet: {}", sheet.getSheetName());
                workbook.removeSheetAt(i);
            }
        }
    }

    // 添加数据到sheet
    private void addDataToSheet(Sheet sheet, Map<String, Object> data, String[] headers) {
        int lastRowNum = sheet.getLastRowNum();
        Row row = sheet.createRow(lastRowNum + 1);

        for (int i = 0; i < headers.length; i++) {
            String header = headers[i];
            Object value = data.get(header);
            Cell cell = row.createCell(i);

            if (value != null) {
                if (value instanceof String) {
                    cell.setCellValue((String) value);
                } else if (value instanceof Number) {
                    cell.setCellValue(((Number) value).doubleValue());
                } else if (value instanceof Date) {
                    cell.setCellValue((Date) value);
                } else {
                    cell.setCellValue(value.toString());
                }
            } else {
                cell.setCellValue("");
            }
        }
    }

    // 获取单元格字符串值
    private String getCellStringValue(Row row, Integer columnIndex) {
        if (columnIndex == null || row == null) {
            return null;
        }
        Cell cell = row.getCell(columnIndex);
        if (cell == null) {
            return null;
        }
        return switch (cell.getCellType()) {
            case STRING -> cell.getStringCellValue().trim();
            case NUMERIC -> String.valueOf((long) cell.getNumericCellValue());
            case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
            default -> null;
        };
    }

    // 各数据源的表头定义
    private String[] getLinkedInHeaders() {
        return new String[]{"公司名", "人名", "网址", "职位", "行业", "邮箱", "电话", "手机号", "位置", "地点", "国家", "公司规模", "twitter用户", "twitter链接", "LinkedIn链接", "GitHub链接", "Facebook链接"};
    }

    private String[] getTwitterHeaders() {
        return new String[]{"姓名", "邮箱", "屏幕名", "粉丝数", "创建时间"};
    }

    /**
     * 下载批量社媒反查模板
     * @param lang 语言（zh/en）
     * @param type 类型（linkedin/twitter）
     */
    @GetMapping("/batch/template")
    public ResponseEntity<byte[]> downloadTemplate(
            @RequestParam(defaultValue = "zh") String lang,
            @RequestParam(defaultValue = "linkedin") String type) {
        try {
            String templatePath;
            String fileName;
            
            if ("en".equals(lang)) {
                if ("twitter".equals(type)) {
                    templatePath = "static/templates/social/social_media_twitter.xls";
                    fileName = "social_media_twitter.xls";
                } else {
                    templatePath = "static/templates/social/social_media_linkedIn.xls";
                    fileName = "social_media_linkedIn.xls";
                }
            } else {
                if ("twitter".equals(type)) {
                    templatePath = "static/templates/social/社媒反查_twitter.xls";
                    fileName = "社媒反查_twitter.xls";
                } else {
                    templatePath = "static/templates/social/社媒反查_linkedIn.xls";
                    fileName = "社媒反查_linkedIn.xls";
                }
            }
            
            Resource resource = new ClassPathResource(templatePath);
            InputStream inputStream = resource.getInputStream();
            byte[] bytes = inputStream.readAllBytes();
            inputStream.close();
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", java.net.URLEncoder.encode(fileName, "UTF-8"));
            headers.setContentLength(bytes.length);
            
            return ResponseEntity.ok().headers(headers).body(bytes);
        } catch (Exception e) {
            log.error("下载模板失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }
} 